#include "data_deal.h"

CDataDeal::CDataDeal(){

}

CDataDeal::~CDataDeal(){

}

void CDataDeal::initialize(CDataStream * n_DataStream){
	m_DataStream = n_DataStream;
}

void CDataDeal::run(){
	start();
}

void CDataDeal::execute(){
	m_AppNode = m_AppNode.openFileHelper(m_FileName, "SV");

	int j = m_AppNode.nChildNode();
	unsigned long FileLength;
	int len = 1;
	for(int i = 0; i < j; ++i){
		m_ChildNode = m_AppNode.getChildNode(i);
		m_FileName = (char *)(m_ChildNode.getText());
		m_File = fopen(m_FileName, "rb");
		fseek(m_File,0,SEEK_END);
		FileLength=ftell(m_File);
		fseek(m_File,0,SEEK_SET);
		m_DataStream->new_file(m_FileName, FileLength);
		while(len){
			len = compress(m_Buffer, m_TempBuf, len);
			m_DataStream->update_len(len);
			m_Buffer = NULL;
			m_Buffer = m_DataStream->update_buf();
			if(!m_Buffer)
				continue;
			len = 0;
			len = fread(m_TempBuf,sizeof(char), 1024,m_File);
		}
	}
}

int CDataDeal::compress(char * outbuf, char * inbuf, int inlen){
	int ret;
	unsigned have;
	z_stream strm;

	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;

	ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
	if (ret != Z_OK)
		return ret;

	strm.avail_in = inlen;
	strm.next_in = (Bytef *)inbuf;

	strm.avail_out = CHUNK;
	strm.next_out = (Bytef *)outbuf;
	ret = deflate(&strm, Z_NO_FLUSH);
	assert(ret != Z_STREAM_ERROR);

	have = CHUNK - strm.avail_out;

	(void)deflateEnd(&strm);

	return have;
}

int CDataDeal::diff(void * buffer, FILE * file){
	return 1;
}